{% extends 'base/base.html' %}
{% load static %}

{% block title %}我的购物车 - 妙趣拾光锦盒{% endblock %}

{% block extra_css %}
<style>
    .cart-item {
        transition: all 0.3s ease;
    }
    
    .cart-item:hover {
        background-color: rgba(214, 183, 255, 0.1);
    }
    
    .cart-item-image {
        width: 80px;
        height: 80px;
        object-fit: cover;
        border-radius: 8px;
        transition: all 0.3s ease;
    }
    
    .cart-item:hover .cart-item-image {
        transform: scale(1.05);
    }
    
    .quantity-control {
        display: flex;
        align-items: center;
        border: 1px solid #ced4da;
        border-radius: 8px;
        overflow: hidden;
        max-width: 120px;
    }
    
    .quantity-control button {
        background-color: #f8f9fa;
        border: none;
        padding: 8px 12px;
        font-size: 14px;
        cursor: pointer;
        transition: all 0.3s ease;
    }
    
    .quantity-control button:hover {
        background-color: #e9ecef;
    }
    
    .quantity-control input {
        border: none;
        text-align: center;
        max-width: 40px;
        padding: 8px 0;
    }
    
    .cart-summary {
        position: sticky;
        top: 80px;
    }
    
    .empty-cart {
        min-height: 300px;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
    }
    
    .empty-cart-icon {
        font-size: 5rem;
        color: #a370f7;
        opacity: 0.3;
        margin-bottom: 20px;
    }
</style>
{% endblock %}

{% block content %}
<section class="py-5">
    <div class="container">
        <h2 class="mb-4">我的购物车</h2>
        
        <div class="row">
            {% if cart_items %}
            <div class="col-lg-8 mb-4">
                <div class="card mb-4 border-0 shadow-sm">
                    <div class="card-header bg-white">
                        <div class="d-flex align-items-center">
                            <div class="form-check">
                                <input class="form-check-input" type="checkbox" id="selectAll" 
                                        {% if cart_items and all_selected %}checked{% endif %}>
                                <label class="form-check-label" for="selectAll">
                                    全选
                                </label>
                            </div>
                            <div class="ms-auto">
                                <button class="btn btn-outline-danger btn-sm" id="clearCart">
                                    <i class="fas fa-trash-alt me-1"></i>清空购物车
                                </button>
                            </div>
                        </div>
                    </div>
                    <div class="card-body p-0">
                        <ul class="list-group list-group-flush">
                            {% for item in cart_items %}
                            <li class="list-group-item border-0 py-3 cart-item" data-item-id="{{ item.cart_item_id }}">
                                <div class="row align-items-center">
                                    <div class="col-auto">
                                        <div class="form-check">
                                            <input class="form-check-input item-select" type="checkbox" 
                                                   id="item{{ item.cart_item_id }}" 
                                                   data-item-id="{{ item.cart_item_id }}"
                                                   {% if item.selected %}checked{% endif %}>
                                        </div>
                                    </div>
                                    <div class="col-auto">
                                        <a href="{% url 'blindbox:detail' box_id=item.box_id %}">
                                            <img src="{{ item.image_url }}" alt="{{ item.name }}" class="cart-item-image shadow-sm">
                                        </a>
                                    </div>
                                    <div class="col">
                                        <h6 class="mb-1">
                                            <a href="{% url 'blindbox:detail' box_id=item.box_id %}" class="text-dark text-decoration-none">
                                                {{ item.name }}
                                            </a>
                                        </h6>
                                        <div class="d-flex flex-wrap">
                                            <span class="badge bg-primary me-2">盲盒</span>
                                            {% if item.quantity > item.stock %}
                                            <span class="badge bg-danger">库存不足</span>
                                            {% endif %}
                                        </div>
                                    </div>
                                    <div class="col-auto">
                                        <div class="text-danger fs-5 fw-bold">¥{{ item.discount_price }}</div>
                                        {% if item.original_price > item.discount_price %}
                                        <div class="text-muted text-decoration-line-through">¥{{ item.original_price }}</div>
                                        {% endif %}
                                    </div>
                                    <div class="col-auto">
                                        <div class="quantity-control">
                                            <button type="button" class="decrease-quantity" data-item-id="{{ item.cart_item_id }}">
                                                <i class="fas fa-minus"></i>
                                            </button>
                                            <input type="text" class="item-quantity" value="{{ item.quantity }}" 
                                                   data-item-id="{{ item.cart_item_id }}"
                                                   min="1" max="{{ item.stock }}">
                                            <button type="button" class="increase-quantity" data-item-id="{{ item.cart_item_id }}">
                                                <i class="fas fa-plus"></i>
                                            </button>
                                        </div>
                                    </div>
                                    <div class="col-auto">
                                        <button type="button" class="btn btn-sm btn-outline-danger remove-item" 
                                                data-item-id="{{ item.cart_item_id }}">
                                            <i class="fas fa-trash"></i>
                                        </button>
                                    </div>
                                </div>
                            </li>
                            {% endfor %}
                        </ul>
                    </div>
                </div>
            </div>
            <div class="col-lg-4">
                <div class="card border-0 shadow-sm cart-summary">
                    <div class="card-header bg-white">
                        <h5 class="mb-0">订单摘要</h5>
                    </div>
                    <div class="card-body">
                        <div class="d-flex justify-content-between mb-2">
                            <span>已选商品：</span>
                            <span id="totalQuantity">{{ total_quantity }} 件</span>
                        </div>
                        <div class="d-flex justify-content-between mb-3">
                            <span>总计：</span>
                            <span class="text-danger fw-bold fs-5" id="totalPrice">¥{{ total_price|floatformat:2 }}</span>
                        </div>
                        <form action="{% url 'shopping:checkout' %}" method="post" id="checkoutForm">
                            {% csrf_token %}
                            <button type="submit" class="btn btn-primary w-100 py-2" id="checkoutBtn"
                                    {% if total_quantity == 0 %}disabled{% endif %}>
                                <i class="fas fa-check me-2"></i>结算
                            </button>
                        </form>
                        
                        <div class="mt-4">
                            <h6 class="mb-3">使用说明</h6>
                            <ul class="list-unstyled text-muted small">
                                <li class="mb-2">
                                    <i class="fas fa-info-circle me-1"></i> 结算前请确认商品和数量
                                </li>
                                <li class="mb-2">
                                    <i class="fas fa-info-circle me-1"></i> 库存不足的商品无法结算
                                </li>
                                <li class="mb-2">
                                    <i class="fas fa-info-circle me-1"></i> 商品价格可能会有变化，请及时结算
                                </li>
                            </ul>
                        </div>
                    </div>
                </div>
            </div>
            {% else %}
            <div class="col-12">
                <div class="card border-0 shadow-sm">
                    <div class="card-body p-5">
                        <div class="empty-cart">
                            <i class="fas fa-shopping-cart empty-cart-icon"></i>
                            <h4 class="mb-3">购物车空空如也</h4>
                            <p class="text-muted mb-4">快去探索更多惊喜盲盒吧！</p>
                            <a href="{% url 'blindbox:list' %}" class="btn btn-primary px-4 py-2">
                                <i class="fas fa-box-open me-2"></i>去选购
                            </a>
                        </div>
                    </div>
                </div>
            </div>
            {% endif %}
        </div>
    </div>
</section>

<!-- 确认删除对话框 -->
<div class="modal fade" id="removeItemModal" tabindex="-1" aria-labelledby="removeItemModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="removeItemModalLabel">确认删除</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                确定要从购物车中删除此商品吗？
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <a href="#" class="btn btn-danger" id="confirmRemove">确认删除</a>
            </div>
        </div>
    </div>
</div>

<!-- 确认清空购物车对话框 -->
<div class="modal fade" id="clearCartModal" tabindex="-1" aria-labelledby="clearCartModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="clearCartModalLabel">确认清空购物车</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                确定要清空购物车中的所有商品吗？此操作不可恢复。
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <form action="{% url 'shopping:clear_cart' %}" method="post" id="clearCartForm">
                    {% csrf_token %}
                    <button type="submit" class="btn btn-danger">确认清空</button>
                </form>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
    $(document).ready(function() {
        // 全选/取消全选
        $('#selectAll').change(function() {
            const isChecked = $(this).prop('checked');
            
            // 显示加载指示器
            showLoading();
            
            $.ajax({
                url: '{% url "shopping:select_all" %}',
                type: 'POST',
                data: {
                    'select_all': isChecked,
                    'csrfmiddlewaretoken': '{{ csrf_token }}'
                },
                success: function(response) {
                    if (response.status === 'success') {
                        // 更新所有复选框状态
                        $('.item-select').prop('checked', isChecked);
                        
                        // 更新总价和数量
                        updateSummary(response.total_price, response.total_quantity);
                        
                        hideLoading();
                    } else {
                        showError(response.message);
                        hideLoading();
                    }
                },
                error: function() {
                    showError('操作失败，请稍后重试');
                    hideLoading();
                }
            });
        });
        
        // 单个商品选择/取消选择
        $('.item-select').change(function() {
            const itemId = $(this).data('item-id');
            
            // 显示加载指示器
            showLoading();
            
            $.ajax({
                url: '{% url "shopping:update_cart" %}',
                type: 'POST',
                data: {
                    'item_id': itemId,
                    'action': 'toggle_select',
                    'csrfmiddlewaretoken': '{{ csrf_token }}'
                },
                success: function(response) {
                    if (response.status === 'success') {
                        // 更新全选状态
                        updateSelectAllStatus();
                        
                        // 更新总价和数量
                        updateSummary(response.total_price, response.total_quantity);
                        
                        hideLoading();
                    } else {
                        showError(response.message);
                        hideLoading();
                    }
                },
                error: function() {
                    showError('操作失败，请稍后重试');
                    hideLoading();
                }
            });
        });
        
        // 减少数量
        $('.decrease-quantity').click(function() {
            var itemId = $(this).data('item-id');
            updateItemQuantity(itemId, 'decrease');
        });
        
        // 增加数量
        $('.increase-quantity').click(function() {
            var itemId = $(this).data('item-id');
            updateItemQuantity(itemId, 'increase');
        });
        
        // 直接输入数量
        $('.item-quantity').change(function() {
            var itemId = $(this).data('item-id');
            var newQuantity = $(this).val();
            
            // 显示加载指示器
            showLoading();
            
            $.ajax({
                url: '{% url "shopping:update_cart" %}',
                type: 'POST',
                data: {
                    'item_id': itemId,
                    'action': 'set_quantity',
                    'quantity': newQuantity,
                    'csrfmiddlewaretoken': '{{ csrf_token }}'
                },
                success: function(response) {
                    if (response.status === 'success') {
                        // 更新总价和数量
                        updateSummary(response.total_price, response.total_quantity);
                        hideLoading();
                    } else {
                        showError(response.message);
                        hideLoading();
                        // 重置数量输入框
                        refreshCart();
                    }
                },
                error: function() {
                    showError('操作失败，请稍后重试');
                    hideLoading();
                    // 重置数量输入框
                    refreshCart();
                }
            });
        });
        
        // 删除商品
        $('.remove-item').click(function() {
            var itemId = $(this).data('item-id');
            $('#confirmRemove').attr('href', '{% url "shopping:cart" %}remove/' + itemId + '/');
            $('#removeItemModal').modal('show');
        });
        
        // 清空购物车
        $('#clearCart').click(function() {
            $('#clearCartModal').modal('show');
        });
        
        // 辅助函数：更新商品数量
        function updateItemQuantity(itemId, action) {
            // 显示加载指示器
            showLoading();
            
            $.ajax({
                url: '{% url "shopping:update_cart" %}',
                type: 'POST',
                data: {
                    'item_id': itemId,
                    'action': action,
                    'csrfmiddlewaretoken': '{{ csrf_token }}'
                },
                success: function(response) {
                    if (response.status === 'success') {
                        // 更新数量显示
                        updateQuantityDisplay(itemId, action);
                        
                        // 更新总价和数量
                        updateSummary(response.total_price, response.total_quantity);
                        
                        hideLoading();
                    } else {
                        showError(response.message);
                        hideLoading();
                    }
                },
                error: function() {
                    showError('操作失败，请稍后重试');
                    hideLoading();
                }
            });
        }
        
        // 辅助函数：更新数量显示
        function updateQuantityDisplay(itemId, action) {
            var inputElem = $('.item-quantity[data-item-id="' + itemId + '"]');
            var currentVal = parseInt(inputElem.val());
            
            if (action === 'increase') {
                inputElem.val(currentVal + 1);
            } else if (action === 'decrease') {
                inputElem.val(currentVal - 1);
            }
        }
        
        // 辅助函数：更新全选状态
        function updateSelectAllStatus() {
            var allChecked = true;
            $('.item-select').each(function() {
                if (!$(this).prop('checked')) {
                    allChecked = false;
                    return false;
                }
            });
            
            $('#selectAll').prop('checked', allChecked);
        }
        
        // 辅助函数：更新总价和数量
        function updateSummary(totalPrice, totalQuantity) {
            $('#totalPrice').text('¥' + totalPrice.toFixed(2));
            $('#totalQuantity').text(totalQuantity + ' 件');
            
            // 启用或禁用结算按钮
            if (totalQuantity > 0) {
                $('#checkoutBtn').prop('disabled', false);
            } else {
                $('#checkoutBtn').prop('disabled', true);
            }
        }
        
        // 辅助函数：显示加载指示器
        function showLoading() {
            // 在这里添加加载指示器的代码
            $('body').addClass('wait');
        }
        
        // 辅助函数：隐藏加载指示器
        function hideLoading() {
            // 在这里隐藏加载指示器的代码
            $('body').removeClass('wait');
        }
        
        // 辅助函数：显示错误消息
        function showError(message) {
            // 创建一个临时提示
            var alert = $('<div class="alert alert-danger alert-dismissible fade show" role="alert">' +
                       '<i class="fas fa-exclamation-circle me-2"></i>' + message +
                       '<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>' +
                       '</div>');
            
            // 添加到页面顶部
            $('.container').prepend(alert);
            
            // 5秒后自动消失
            setTimeout(function() {
                alert.alert('close');
            }, 5000);
        }
        
        // 辅助函数：刷新购物车
        function refreshCart() {
            location.reload();
        }
    });
</script>
{% endblock %} 